<template>
	<view class="page">
		<image src="@/static/report.png" class="bg" />
		<uv-navbar :title="scrollTop > 120 ? reportInfo.name : ''" placeholder
			:bg-color="scrollTop > 120 ? '#fff' : 'transparent'" auto-back
			:left-icon-color="scrollTop > 120 ? '#757575' : '#fff'" title-style="color: #000000; font-size: 32rpx" />
		<view class="name ss-font-38">
			{{ reportInfo.name || "-" }}
		</view>

		<view class="list ss-r-20 ss-size ss-shadow ss-font-28 ss-bg-w">
			<view class="list_box ss-flex">
				<view class="list_box_l">客户名称：</view>
				<view>{{ reportInfo.customerName || "-" }}</view>
			</view>
			<view class="list_box ss-flex">
				<view class="list_box_l">发起人员：</view>
				<view>{{ reportInfo.nickName || "-" }}</view>
			</view>
			<view class="list_box ss-flex">
				<view class="list_box_l">报告类型：</view>
				<view v-if="reportInfo.planBeginTime">
					{{ reportInfo.planBeginTime.split("-")[0] }}年{{
            reportInfo.planBeginTime.split("-")[1]
          }}月维保报告
				</view>
				<view class="" v-else>-</view>
			</view>
			<view class="list_box ss-flex">
				<view class="list_box_l">提交时间：</view>
				<view>{{ reportInfo.createTime || "-" }}</view>
			</view>
			<view class="list_box ss-flex">
				<view class="list_box_l">项目状态：</view>
				<view>{{ reportInfo.finishStatus == 1 ? "已完成" : "未完成" }}</view>
			</view>
		</view>
		<view class="tabCard ss-r-20 ss-shadow ss-font-28 ss-bg-w">
			<view class="ss-flex ss-grey-1 bb">
				<view class="tab_list ss-font-28 ss-p-24" v-for="(i, index) in tabList" :key="index" :style="{
            backgroundColor: currentTab == index ? '#4EA770' : '#fff',
            color: currentTab == index ? '#fff' : '#000',
          }" @click="changeTab(index)">
					{{ i.name }}
				</view>
			</view>
			<view class="ss-p-26 ss-bg-w" v-if="currentTab == 0">
				<uv-empty v-if="reportInfo.passStatus == 1" :customStyle="{ margin: '10vh auto' }" :icon="allPass"
					text="本次设施设备检查全部合格" />
				<view v-else>
					<view class="ss-flex ss-col-center ss-m-y-10">
						<view class="tabCard_l"></view>
						<view class="ss-m-x-10 ss-black ss-font-28">存在问题与诊断建议</view>
					</view>
					<view v-for="(i, index) in sysList" :key="index">
						<view class="ss-grey-2 ss-m-y-16">
							<view class="ss-m-y-16 ss-m-x-6"> 维护保养内容 </view>
							<view class="ss-m-y-16 inputBox ss-p-16">
								{{ i.systemName || "-" }}
							</view>
						</view>
						<view class="ss-grey-2 ss-m-x-6 ss-m-y-16" @click="handleEdit(i)">
							<view class="ss-m-y-16 textColorSty"> 设备{{ index + 1 }} </view>
							<view class="ss-m-y-16 inputBox ss-p-16">
								{{ i.systemDeviceName || "-" }}
							</view>
						</view>
						<view class="ss-grey-2 ss-m-x-6 ss-m-y-16" @click="handleEdit(i)">
							<view class="ss-m-y-16"> 检查项 </view>
							<view class="ss-m-y-16 inputBox ss-p-16">
								{{ i.deviceItemName || "-" }}
							</view>
						</view>
						<view class="ss-grey-2 ss-m-x-6 ss-m-y-16" @click="handleEdit(i)">
							<view class="ss-m-y-16"> 现场存在的问题 </view>
							<view class="ss-m-y-16 inputBox ss-p-16">
								{{ i.content || "-" }}
							</view>
						</view>
						<view class="ss-grey-2 ss-m-x-6 ss-m-y-16" @click="handleEdit(i)">
							<view class="ss-m-y-16"> 地址 </view>
							<view class="ss-m-y-16 inputBox ss-p-16">
								{{ i.buildingFloorName || "-" }}
							</view>
						</view>
						<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
							<view class="ss-m-y-16"> 现场照片 </view>
							<uv-image v-for="(item, index) in i.imgList" :key="index" :src="webSrc(item)"
								@click="previewImage(index, i.imgList)" width="160rpx" height="160rpx" radius="10rpx"
								style="display: inline-block; margin: 0 10rpx 10rpx 0" />
						</view>
						<view class="ss-grey-2 ss-m-x-6 ss-m-y-16" @click="handleEdit(i)">
							<view class="ss-m-y-16"> 备注 </view>
							<view class="ss-m-y-16 inputBox ss-p-16">
								{{ i.remark || "-" }}
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-else class="ss-bg-w">
				<Pdf :list="fileList" />
			</view>
		</view>
		<view class="hun" v-if="currentTab == 0" />
		<view class="func_btn" v-if="functionList.length > 0">
			<view class="btn_con" v-for="(i, k) in functionList" :key="k" @click="handleCommand(i)">
				<uv-icon :name="i.icon" size="40rpx" :label="i.label" label-size="24rpx" label-color="#212121"
					label-pos="bottom" space="10rpx" />
			</view>
		</view>
		<uv-overlay :show="showPop" v-if="showPop">
			<view class="warp">
				<view class="rect ss-r-20" @tap.stop :style="{ width: '580rpx' }">
					<view class="ss-font-32 ss-m-y-20 ss-m-x-30"> 请输入理由 </view>
					<view class="ss-m-y-10 ss-m-x-30 ss-font-26">
						<uv-textarea v-model="reasonForRefusal" placeholder="请输入内容" />
					</view>
					<view class="rect_line"></view>
					<view class="ss-flex ss-row-between ss-col-center ss-font-28">
						<view class="rect_btn ss-m-x-20 ss-m-y-20" @click="showPop = false">取消</view>
						<view class="btn_line ss-m-x-10"></view>
						<view class="rect_btn ss-m-x-20 ss-m-y-20" style="color: #4ea770" @click="handleReturn">
							确定
						</view>
					</view>
				</view>
			</view>
		</uv-overlay>
		<uv-popup ref="editRef" closeable :round="8" :close-on-click-overlay="false">
			<view>
				<view style="width: 640rpx; padding: 20rpx">
					<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
						<view class="ss-m-y-16"> 设备名称 </view>
						<uv-input v-model="editForm.systemDeviceName" disabled placeholder="-" />
					</view>
					<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
						<view class="ss-m-y-16"> 检查项 </view>
						<uv-input v-model="editForm.deviceItemName" disabled placeholder="-" />
					</view>
					<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
						<view class="ss-m-y-16"> 现场存在的问题 </view>
						<uv-input v-model="editForm.content" placeholder="请输入" />
					</view>
					<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
						<view class="ss-m-y-16"> 地址 </view>
						<uv-input v-model="editForm.buildingFloorName" disabled placeholder="-" />
					</view>
					<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
						<view class="ss-m-y-16"> 现场照片 </view>
						<g-upload v-model:value="editForm.photo" multiple :max="9" text="上传" />
					</view>
					<view class="ss-grey-2 ss-m-x-6 ss-m-y-16">
						<view class="ss-m-y-16"> 备注 </view>
						<uv-input v-model="editForm.remark" placeholder="请输入" />
					</view>
				</view>
				<view class="bottom-btn" @click="handleSave">保 存</view>
			</view>
		</uv-popup>
		<uv-back-top :scroll-top="scrollTop" icon="arrow-up" :top="120" />
		
	</view>
</template>
<script setup>
	import {
		ref,
		onMounted,
		onBeforeUnmount
	} from "vue";
	import {
		onLoad,
		onPageScroll
	} from "@dcloudio/uni-app";
	import Pdf from "@/components/PdfList/PdfList.vue";
	import {
		webSrc
	} from "@/common/mothed.js";
	import {
		createDirectory
	} from "@/request/common.js";
	import {
		reportDetails,
		annexList,
		reportReview,
		updateReport
	} from "@/request/task.js";
	import iconSave from "@/static/order/icon_save.png"; // 提交保存
	import iconRefuse from "@/static/order/icon_refuse.png"; // 退回
	import iconDownload from "@/static/order/icon_download.png"; // 下载
	import allPass from "@/static/allPass.png";

	const sysList = ref([]); //列表数据
	const arrList = ref([]); //接口返回列表数据
	const reportId = ref(""); // 报告id
	const reportInfo = ref({});
	const showPop = ref(false); // 退回弹窗
	const currentTab = ref(0); // 当前tab
	const tabList = ref([{
			id: 0,
			name: "诊断详情"
		},
		{
			id: 1,
			name: "相关附件"
		},
	]);
	const functionList = ref([]); // 功能按钮列表
	const reasonForRefusal = ref(""); // 退回原因
	const fileList = ref([]); // 附件列表
	const editRef = ref(); // 编辑弹窗ref
	const editForm = ref({}); // 编辑表单
	const scrollTop = ref(0); // 滚动条位置
	const userInfo = ref({}); // 用户信息

	onLoad(async (e) => {
		reportId.value = e.id || "";
		await getDetails();
		getFunctionList();
	});

	onMounted(() => {
		userInfo.value = uni.getStorageSync("userInfo");
		uni.$on("report", async () => {
			uni.$emit("taskReport");
			await getDetails();
			getFunctionList();
		});
	});

	onBeforeUnmount(() => {
		uni.$off("report");
	});

	onPageScroll((e) => {
		scrollTop.value = Math.floor(e.scrollTop);
	});

	// 获取功能按钮列表
	const getFunctionList = () => {
		const {
			status,
			qualifiedForReview,
			projectLeader
		} = reportInfo.value; // status 1待签字 2待审核 3审核通过 4审核拒绝 5业主通过 6业主拒绝 qualifiedForReview 1可审核 2不可审核
		let list = [];
		if ([1, 4, 6].includes(status) && projectLeader == userInfo.value.userId) {
			list.push({
				label: "提交备注并签字",
				icon: iconSave,
				type: 2,
			});
		}
		if (status == 2 && qualifiedForReview == 1) {
			list.push({
				label: "提交备注并签字",
				icon: iconSave,
				type: 3,
			});
			list.push({
				label: "审核退回",
				icon: iconRefuse,
				type: 4,
			});
		}
		if (status != 1) {
			list.push({
				label: "下载报告",
				icon: iconDownload,
				type: 1,
			});
		}
		functionList.value = list;
	};

	// 获取附件列表
	const getList = () => {
		annexList(reportId.value).then((res) => {
			if (res.code == 200) {
				fileList.value = res.data || [];
			}
		});
	};

	// 获取详情
	const getDetails = async () => {
		const res = await reportDetails(reportId.value);
		uni.$emit("taskReport");
		if (res.code == 200) {
			let index = 0;
			let lastId = {};
			reportInfo.value = res.data;
			sysList.value = res.data?.reportDefectList?.map((item) => {
				const isSameId = lastId.id === item.id;
				if (!isSameId) {
					index = 0;
				}
				index += isSameId ? 1 : 0;
				lastId.id = item.id;
				return {
					...item,
					imgList: item.photo ? item.photo.split(",") : [],
					index,
				};
			});

			arrList.value = sysList.value;
		}
	};

	// 操作
	const handleCommand = (item) => {
		switch (item.type) {
			case 1:
				// 下载报告
				reportInfo.value.reportPdfPath ?
					downloadFile() :
					uni.showToast({
						title: "暂无报告",
						icon: "none",
					});
				break;
			case 2:
				// 签字保存并提交
			case 3:
				// 签字保存
				uni.navigateTo({
					url: `/pages/sign/signature?id=${reportInfo.value.id}&type=${item.type}`,
				});
				break;
			case 4:
				// 审批退回
				showPop.value = true;
				break;
		}
	};

	/* 退回 */
	const handleReturn = () => {
		reportReview({
			id: reportInfo.value.id,
			status: 4,
			reasonForRefusal: reasonForRefusal.value,
		}).then((res) => {
			if (res.code == 200) {
				uni.showToast({
					title: "提交成功",
					icon: "none",
				});
				showPop.value = false;
				reasonForRefusal.value = "";
				uni.$emit("report");
			}
		});
	};

	// 编辑报告
	const handleEdit = (row) => {
		editForm.value = Object.assign({}, row);
		editForm.value.photo = row.imgList || [];
		delete editForm.value.imgList;
		editRef.value.open();
	};

	// 保存编辑
	const handleSave = () => {
		let data = Object.assign({}, editForm.value);
		data.photo = data.photo ? data.photo.join(",") : '';
		updateReport(data).then((res) => {
			if (res.code == 200) {
				editForm.value = {};
				editRef.value.close();
				getDetails();
			}
		});
	};

	// 下载维保报告
	const downloadFile = () => {
		// #ifdef APP-PLUS 
		createDirectory(
			"/Download/",
			(msg) => {
				var url = webSrc(reportInfo.value.reportPdfPath);
				let name = url.substring(url.lastIndexOf("/") + 1);
				let dtask = plus.downloader.createDownload(
					url, {
						filename: "file://storage/emulated/0/Download/" + name,
					},
					(d, status) => {
						//d为下载的文件对象
						if (status == 200) {
							uni.showToast({
								icon: "none",
								mask: true,
								title: "已保存到文件夹：/Download/" + name, //保存路径
								duration: 5000,
							});
							let localpath = plus.io.convertLocalFileSystemURL(d.filename);
							plus.runtime.openFile(d.filename);
						} else {
							plus.downloader.clear(); //清除下载任务
							uni.showToast({
								icon: "none",
								title: "下载失败，请稍后重试",
							});
						}
					}
				);
				dtask.start();
			},
			(err) => {
				console.log(err, '>>>>下载失败');
			}
		);
		// #endif
		/* #ifdef H5 */
		uni.downloadFile({
			url: webSrc(reportInfo.value.reportPdfPath),
			success: (res) => {
				uni.saveFile({
					tempFilePath: res.tempFilePath,
					success: () => {
						uni.showToast({
							title: "下载成功！",
							icon: "none",
						});
					},
				});
			},
			fail: () => {
				console.log('>>>>>失败了');
			}
		});
		/* #endif */
	};

	// 切换tab
	const changeTab = (e) => {
		currentTab.value = e;
		if (currentTab.value == 1) {
			getList();
		}
	};

	// 预览图片
	const previewImage = (index, urls) => {
		uni.previewImage({
			current: index,
			urls: urls.map((i) => webSrc(i)),
		});
	};
</script>
<style lang="scss" scoped>
	@import "@/uni.scss";

	.page {
		width: 100%;
		height: 100%;
		box-sizing: border-box;
	}

	.textColorSty {
		color: #4ea770;
	}

	.bg {
		width: 100%;
		height: 25vh;
		position: fixed;
		top: 0;
		z-index: -10;
	}

	.hun {
		height: 200rpx;
	}

	.inputBox {
		border: 2rpx solid #dedede;
		border-radius: 6rpx;
	}

	.bottom-btn {
		width: 100%;
		height: 80rpx;
		display: flex;
		color: #fff;
		font-size: 28rpx;
		background-color: #4ea770;
		justify-content: center;
		align-items: center;

		&:active {
			background-color: #55b379;
		}
	}

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {
		background-color: #fff;

		.rect_line {
			margin-top: 20rpx;
			width: 100%;
			height: 2rpx;
			background: #e5e5e5;
		}

		.rect_btn {
			width: 48%;
			text-align: center;
		}

		.btn_line {
			height: 70rpx;
			width: 2rpx;
			background: #e5e5e5;
		}
	}

	.list {
		width: 90%;
		text-align: center;
		margin: 40rpx;
		color: #000;
		background: #fff;

		.list_box {
			border-bottom: 1rpx solid #dedede;
			padding: 28rpx 40rpx;

			&:last-child {
				border-bottom: none;
			}

			.list_box_l {
				color: #757575;
			}
		}
	}

	.name {
		width: 100%;
		text-align: center;
		margin: 100rpx auto 60rpx;
		color: #fff;
	}

	.bb {
		border-bottom: 2rpx solid #dedede;
	}

	.tabCard {
		width: 90%;
		overflow: hidden;
		margin: 20rpx 40rpx;

		.tab_list {
			text-align: center;
			width: 48%;
		}

		.tabCard_l {
			height: 30rpx;
			width: 6rpx;
			background: #4ea770;
		}
	}

	.func_btn {
		position: fixed;
		left: 40rpx;
		right: 40rpx;
		bottom: 40rpx;
		z-index: 9;
		height: 120rpx;
		background: #ffffff;
		box-shadow: 0 0 30rpx 2rpx rgba(94, 94, 94, 0.16);
		border-radius: 60rpx;
		display: flex;
		align-items: center;

		.btn_con {
			flex: 1;
			text-align: center;
			border-right: 1rpx solid #dedede;

			&:last-child {
				border-right: none;
			}
		}
	}
</style>